#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"


#include "MQTTClient.h" //mqtt三方库
#include "cJSON.h"      //cJson解析三方库

#include "iot_gpio.h"
#include "hi_io.h"
#include "hi_gpio.h"


#include "wifi_connecter.h" // easy wifi (station模式)
#include "iot_watchdog.h" 

// #include "ssd1306.h"        // OLED驱动接口

static unsigned char sendBuf[1000];
static unsigned char readBuf[1000];
    
// 定义一个宏，用于标识SSID。请根据实际情况修改
#define PARAM_HOTSPOT_SSID "1"

// 定义一个宏，用于标识密码。请根据实际情况修改
#define PARAM_HOTSPOT_PSK "12345678"

// 定义一个宏，用于标识加密方式
#define PARAM_HOTSPOT_TYPE WIFI_SEC_TYPE_PSK



// 定义一个宏，用于标识MQTT服务器IP地址。请根据实际情况修改
#define HOST_ADDR "59e62b5755.st1.iotda-device.cn-north-4.myhuaweicloud.com"

// 定义一个宏，用于标识MQTT服务器端口
#define HOST_PORT 1883

// 定义一个宏，用于标识智能家居的设备ID
#define DEVICE_ID "67eb96a85367f573f77e8956_DEVICE-TEST-001"
// 定义一个宏，用于标识用于MQTT连接的clientid
#define MQTT_CLIENT_ID "67eb96a85367f573f77e8956_DEVICE-TEST-001_0_0_2025040706"

// 定义一个宏，用于标识用于MQTT连接的username
#define MQTT_USERNAME "67eb96a85367f573f77e8956_DEVICE-TEST-001"

// 定义一个宏，用于标识用于MQTT连接的password
#define MQTT_PASSWORD "a0e87ed814b750a189fcfbc1206361c668c9ac87e90a6a66f51ce1ff02613e82"



// 定义一个宏，用于标识设备属性上报所用的topic
#define PUBLISH_TOPIC "$oc/devices/"DEVICE_ID"/sys/properties/report"
// 定义一个宏，用于标识订阅下发命令所用的topic
#define SUBCRIB_TOPIC "$oc/devices/"DEVICE_ID"/sys/commands/#" 
// 定义一个宏，用于标识执行完成下发命令所返回响应的topic
#define RESPONSE_TOPIC "$oc/devices/"DEVICE_ID"/sys/commands/response" 


//定义用于mqtt连接的两个对象变量，对象类型来自mqtt三方库
Network network;    
MQTTClient client;


#define FAN_TASK_GPIO   (9)
#define GPIO_HIGH       (1)
#define GPIO_LOW        (0)

void GpioFAN(void)
{
   
        //设置FAN_TASK_GPIO为高电平
        IoTGpioSetOutputVal(FAN_TASK_GPIO, 1);
   
}

void GpioFAN01(void)
{
    
        //设置FAN_TASK_GPIO为高电平
        IoTGpioSetOutputVal(FAN_TASK_GPIO, 0);
        printf("FAN_OFF\n");

    
}

// 消息到达的回调函数
void messageArrived(MessageData* data) {
    printf("10000\n");
    // 解析JSON数据
    cJSON *root = cJSON_ParseWithLength((char *)data->message->payload, data->message->payloadlen);
    if (root == NULL) {
        printf("Error parsing JSON\n");
        return;
    }
    printf("20000\n");
    // 获取命令名称
    cJSON *cmd_name = cJSON_GetObjectItem(root, "command_name");
     if (cmd_name == NULL) {
        cJSON_Delete(root);
    }
    printf("30000\n");
    if (strcmp(cJSON_GetStringValue(cmd_name), "FanFlag") == 0) {
         cJSON *paras =cJSON_GetObjectItem(root, "paras");
        if (paras == NULL) {
            cJSON_Delete(root);
        }
        cJSON *para = cJSON_GetObjectItem(paras, "flagValue");
        if (para == NULL) {
            cJSON_Delete(root);
        }
        if (strcmp(cJSON_GetStringValue(para), "NO") == 0) {//数据类型：string

            GpioFAN();
            printf("GpioFAN is successful!\n");
        } 
        if (strcmp(cJSON_GetStringValue(para), "OFF") == 0) {//数据类型：string

            GpioFAN01();
            printf("GpioFAN is successful!\n");
        } 
       
    } else {
        printf("Unknown command or missing command_name\n");
    }

    // 清理JSON
    cJSON_Delete(root);
}


    
    static void MQTTDemoTask(void)
{
    //初始化FAN_TASK_GPIO
    IoTGpioInit(FAN_TASK_GPIO);
    //设置FAN_TASK_GPIO为输出模式
    IoTGpioSetDir(FAN_TASK_GPIO, IOT_GPIO_DIR_OUT);
    //把FAN_TASK_GPIO复用在GPIO9
    hi_io_set_func(FAN_TASK_GPIO, HI_IO_FUNC_GPIO_9_GPIO);

    printf(">> MQTTDemoTask ...\n");

    // 连接AP
    // 定义热点配置
    WifiDeviceConfig config = {0};
    // 设置热点配置中的SSID
    strcpy(config.ssid, PARAM_HOTSPOT_SSID);
    // 设置热点配置中的密码
    strcpy(config.preSharedKey, PARAM_HOTSPOT_PSK);
    // 设置热点配置中的加密方式
    config.securityType = PARAM_HOTSPOT_TYPE;
    // 等待100ms
    osDelay(10);
    // 连接到热点
    int netId = ConnectToHotspot(&config);

    printf("wifi connect successful !\n");
    
    // 检查是否成功连接到热点
    if (netId < 0)
    {
        printf("Connect to AP failed!\r\n");
        return;
    }

    // 初始化并启动MQTT任务，连接MQTT服务器
    int rc, count = 0;
begin:  
    NetworkInit(&network);
    NetworkConnect(&network, HOST_ADDR, HOST_PORT);
    printf("MQTTClientInit  ...\n");
    MQTTClientInit(&client, &network, 2000, sendBuf, sizeof(sendBuf), readBuf, sizeof(readBuf));
    MQTTString clientId = MQTTString_initializer;
    clientId.cstring = MQTT_CLIENT_ID;
    MQTTString userName = MQTTString_initializer;
    userName.cstring = MQTT_USERNAME;
    MQTTString password = MQTTString_initializer;
    password.cstring = MQTT_PASSWORD;
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.clientID = clientId;
    data.username = userName;
	data.password = password;
    data.willFlag = 0;
    data.MQTTVersion = 4;
    data.keepAliveInterval = 60;
    data.cleansession = 1;
    printf("MQTTConnect  ...\n");
    rc = MQTTConnect(&client, &data);
    if (rc != 0) {
        printf("MQTTConnect: %d\n", rc);
        NetworkDisconnect(&network);
        MQTTDisconnect(&client);
        goto begin;
    }


    printf("MQTTSubscribe  ...\n");
    rc = MQTTSubscribe(&client, SUBCRIB_TOPIC, 0, messageArrived);
    printf("==============================>rc  %d\n",rc);
    if (rc != 0) {
        printf("MQTTSubscribe: %d\n", rc);
        osDelay(200);
        goto begin;
    }

    while(1){
        MQTTYield(&client, 5000);
    }
}  


static void OC_Demo(void)
{
    // IoTWatchDogDisable();
    osThreadAttr_t attr;

    attr.name = "MQTTDemoTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 24;
    printf("aaaaa\n");
    if (osThreadNew((osThreadFunc_t)MQTTDemoTask, NULL, &attr) == NULL)
    {
        printf("Falied to create MQTTDemoTask!\n");
    }

}




APP_FEATURE_INIT(OC_Demo);
//SYS_RUN(OC_Demo);

